package com.leo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * @ClassName ClipboardDemo
 * @Description 剪切板
 * @Author wangss
 * @date 2020.06.05 13:34
 * @Version 1.0
 */
public class ClipboardDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(an);

        Clipboard clipboard = Clipboard.getSystemClipboard();

        /*ClipboardContent content = new ClipboardContent();
        content.put(DataFormat.PLAIN_TEXT, "12345");
        clipboard.setContent(content);*/

        Label label = new Label("等待粘贴内容");


        ImageView iv = new ImageView();
        iv.setPreserveRatio(true);
        iv.setFitWidth(300d);
        iv.setFitHeight(300d);

        AnchorPane.setLeftAnchor(iv, 300d);
        an.getChildren().addAll(label, iv);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ImageViewDemo");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
        primaryStage.setResizable(false);
        primaryStage.show();

        KeyCodeCombination kc = new KeyCodeCombination(KeyCode.V, KeyCodeCombination.CONTROL_DOWN);
        scene.getAccelerators().put(kc, () -> {
            if (clipboard.hasString()) {
                label.setText(clipboard.getString());
            }

            // 复制一个图片文件，其实是一个文件，所以使用这个来判断
            if (clipboard.hasFiles()) {
                List<File> files = clipboard.getFiles();
                Image image = null;
                try {
                    image = new Image(new FileInputStream(files.get(0)));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                iv.setImage(image);
            }

            // 通过剪切工具获得的图片，可以用这个判断
            if (clipboard.hasImage()) {
                iv.setImage(clipboard.getImage());
            }
        });
    }
}
